﻿namespace Growatt.ShinebusServiceUploadPack.Service.FeishuHelper
{
    using Microsoft.Extensions.Http;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json;
    using System;
    using System.Buffers.Text;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;

    public abstract class BaseHttpClient
    {
        protected string baseID = string.Empty;
        protected string tablesID = string.Empty;
        protected string accessToken = string.Empty;
        protected string ViewId = string.Empty;

        protected readonly IHttpClientFactory _httpClientFactory;
        protected readonly string BaseAddress = "https://open.feishu.cn/open-apis/";
        protected  string urlUploadFileFieshuUrl = "https://q02gj5lyidv.feishu.cn/base/Ou1JbCNtKaOXEAsNq83ceyVwn0e?table=tblb8JSTNrW6aXqX&view=vewZhMLj6Q";

        public BaseHttpClient(IHttpClientFactory httpClientFactory, string urlUploadFileFieshuUrl)
        {
            _httpClientFactory = httpClientFactory;
            this.urlUploadFileFieshuUrl = urlUploadFileFieshuUrl;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="urlUploadFileFieshuUrl"></param>
        public void UpdateIDs(string urlUploadFileFieshuUrlTemp)
        {
            // 解析飞书URL获取基础ID、表ID和视图ID
            var (baseIdUploadFile, tableIdUploadFile, viewIdUploadFile) = FeishuInfoRequest.ParseFeishuUrl(urlUploadFileFieshuUrlTemp);
            urlUploadFileFieshuUrl = urlUploadFileFieshuUrlTemp;
            baseID = baseIdUploadFile;
            tablesID = tableIdUploadFile;
            ViewId = viewIdUploadFile;
        }
        protected async Task<string> SendPostRequestAsync(string url, HttpContent content, ILogger logger, string accessToken)
        {
            using (HttpClient client = _httpClientFactory.CreateClient("OSS"))
            {
                // 设置请求头
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                // 发送 POST 请求
                try
                {
                    var response = await client.PostAsync(url, content);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        return responseContent;
                    }
                    else
                    {
                        logger.LogInformation("请求失败，状态码：" + response.StatusCode);
                        logger.LogInformation(responseContent);
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError($"请求过程出错：{ex.Message}");
                }
            }
            return string.Empty;
        }

        protected async Task<string> SendPutRequestAsync(string url, HttpContent content, ILogger logger, string accessToken)
        {
            using (HttpClient client = _httpClientFactory.CreateClient("OSS"))
            {
                // 设置请求头
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                // 发送 PUT 请求
                try
                {
                    var response = await client.PutAsync(url, content);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        return responseContent;
                    }
                    else
                    {
                        logger.LogInformation("请求失败，状态码：" + response.StatusCode);
                        logger.LogInformation(responseContent);
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError($"请求过程出错：{ex.Message}");
                }
            }
            return string.Empty;
        }
    }

}
